package com.lishem.rpc.server.zk;

import com.lishem.common.annotation.RpcService;
import com.lishem.common.utils.IpUtil;
import com.lishem.common.utils.SpringBeanFactory;
import com.lishem.rpc.server.config.RpcServerConfiguration;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Zookeeper服务连接注册管理
 */
@Component
public class ServicePushManager {

    private static final Logger LOGGER = LoggerFactory.getLogger(ServicePushManager.class);

    @Autowired
    private ZKit zKit;

    @Autowired
    private RpcServerConfiguration configuration;

    /**
     * 服务注册接口
     */
    public void registerIntoZK() {
        //1.找到所有有@RpcService注解的类
        Map<String, Object> beanListByAnnotationClass =
                SpringBeanFactory.getBeanListByAnnotationClass(RpcService.class);

        if(!MapUtils.isEmpty(beanListByAnnotationClass)){
            //根节点创建
            zKit.createRootNode();
            for (Object bean : beanListByAnnotationClass.values()) {
                //2.获取每个类上的注解@RpcService.cls的值
                RpcService annotation = bean.getClass().getAnnotation(RpcService.class);
                Class<?> clazz = annotation.cls();
                //3.获取cls的之后，将它的name作为节点名字，注册到Zookeeper中(在rpc节点下创建一个子节点)
                String serviceName = clazz.getName();
                //创建接口对应的节点
                zKit.createPersistentNode(serviceName);
                //3.同时为每个节点创建一个子节点  IP：HttpPort：RpcPort
                String serviceAddress =
                        IpUtil.getRealIp()+
                                ":"+configuration.getServerPort()+
                                ":"+configuration.getNetworkPort();
                zKit.createNode(serviceName+"/"+serviceAddress);
            }
        }
    }
}
